<?
include "../db_config.php";

$sql = "select * from wps_ap_detection_log order by logId desc";
$result = mysql_query($sql);
$d = mysql_fetch_array($result);

$lat = $HTTP_GET_VARS['lat'];
$lng = $HTTP_GET_VARS['lng'];

if($lat == null)
	$lat = $d[latitude];
if($lng == null)
	$lng = $d[longitude];

?>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>AP 위치 측정 in Google by Chaehyun Lee</title>

<!-- for iphone & android phone -->
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />

<style type="text/css">
body{
	 margin:0px; 
	 padding:0px;
}
#waiting{
	position:absolute;
	top:50%;
	left:50%;
	visibility:hidden;
	background-color:white;
	z-index:100;
}
#totalNum{
	position:absolute;
	top:0px;
	left:0px;
}
#infoWin{
	position:absolute;
	top:0px;
	left:100px;
	background-color:white;
	margin:0px 10px 10px 10px;
	z-index:100;
}
#infoWin2{
	position:absolute;
	top:0px;
	left:400px;
	background-color:white;
	margin:0px 10px 10px 10px;
	z-index:100;
}

#rulerButton{
	position:absolute;
	top:0px;
	left:500px;
	width:50px;
	height:50px;
	background-color:white;
	z-index:100;
}
.distance{
	background-color:white;
}


</style>


<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var mapObj;
var mapBounds;
var markers  = new Array();
var dragStatus = false;
var donotChangeMap = 0;
function initialize() {

<?
if($lat != null && $lng != null)
	echo "\tvar center = new google.maps.LatLng($lat, $lng);\n";
else
	echo "\tvar center = new google.maps.LatLng(37.5803883	,126.8871283);\n";
?>
 
    //var latlng = new google.maps.LatLng(-34.397, 150.644);
    var myOptions = {
      zoom: 18,
      center: center,
      //mapTypeId: google.maps.MapTypeId.ROADMAP
      mapTypeId: google.maps.MapTypeId.HYBRID
    };
    mapObj = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	//google.maps.event.addListener(mapObj, "bounds_changed", boundsChanged);

	getAPPoints();

	//do not fire bounds_changed event every time when dragged
	//fire only one 'moveend' event when dragging & zoom is ended
	google.maps.event.addListener(mapObj, "bounds_changed", function()
	{
		function finished(){
			google.maps.event.trigger(mapObj, 'moveend');
		}
		clearTimeout(this.timeout);
		this.timeout = setTimeout(finished, 200);
	});
	google.maps.event.addListener(mapObj, "moveend", getAPPoints);
	//google.maps.event.addListener(mapObj, "bounds_changed", getAPPoints);
	//google.maps.event.addListener(mapObj, "click", rulerCheck);
	//google.maps.event.addListener(mapObj, "dragend", getAPPoints);
	//google.maps.event.addListener(mapObj, "zoom_changed", getAPPoints);
	//google.maps.event.addListener(mapObj, "zoomend", getAPPoints);

}
function GetXmlHttpObject()
{
	if (window.XMLHttpRequest)
	  {
	  // code for IE7+, Firefox, Chrome, Opera, Safari
		  return new XMLHttpRequest();
	  }
	else if (window.ActiveXObject)
	  {
	  // code for IE6, IE5
		//return new ActiveXObject("Microsoft.XMLHTTP");
	  	  return new ActiveXObject('MSXML2.XMLHTTP.3.0');
	  }
	return null;
}
function boundsChanged(a, b, c)
{
	mapBounds = mapObj.getBounds();
}

function clearMarkers()
{
	for(var i = 0; i < markers.length; i++)
	{
		markers[i].setMap(null);
		markers[i] = null;
	}
	markers.length = 0;
}
function addmarker(x, y, i, snr, viewOnPoint)
{
	var n1, n2;

	var pt_img = "http://ozs.kr/lbs/point.png";
	var base_img = "http://static.naver.com/maps/mymap/ico_traffic_";

	var no_img_url = "http://static.naver.com/maps/ico_spot"+i+".gif";


	n1 = new google.maps.LatLng(x, y);


	if(viewOnPoint == undefined)
	{
		var pt = new google.maps.Marker({
			position:n1,
			map:mapObj,
			icon:pt_img,
		});

		//number image which represents total ap number on that point
		var no_img = new google.maps.MarkerImage(no_img_url,
			new google.maps.Size(21, 18),
			new google.maps.Point(0, 0),
			new google.maps.Point(11, 25));

		var no_ic = new google.maps.Marker({
			position:n1, 
			map:mapObj,
			icon:no_img,
		});
	}
	else
	{
		var no_ic = new google.maps.Marker({
			position:n1,
			map:mapObj,
			icon:pt_img,
		});
	}

		
	var infoWindow = new google.maps.InfoWindow({
		content:snr,
		disableAutoPan:true
	});

	google.maps.event.addListener(no_ic, 'click', function(){
		infoWindow.open(mapObj, no_ic);
		//mark this window is clicked
		infoWindow.setZIndex(1);
	});

	google.maps.event.addListener(no_ic, 'mouseover', function(){
		infoWindow.open(mapObj, no_ic);
	});
	google.maps.event.addListener(no_ic, 'mouseout', function(){
		//do not close window if it is clicked
		if(infoWindow.getZIndex() != 1)
		{
			infoWindow.close();
		}
	});



	//save all markers
	if(viewOnPoint == undefined)
		markers.push(pt);
	markers.push(no_ic);


	//infowin.set(n2, "<div style='width:20px;height:20px;'>"+snr+"</div>");
	
	return;

	n1 = new GLatLng(x, y);

	n2 = new GLatLng(x, y+0.00005);

	var size = new GSize(21, 18);
	var offset = new GSize(10, 18);


	var size2 = new GSize(7, 8);
	//var pt = new GMarker(n1, new GIcon(pt_img, size2));
	var ic = new GIcon(G_DEFAULT_ICON);
	ic.image = pt_img;
	ic.iconSize = size2;
	ic.iconAnchor = new GPoint(10, 18);
	ic.shadowSize = new GSize(0, 0);
	var pt = new GMarker(n1, ic);
	mapObj.addOverlay(pt);

/*
	if(viewOnPoint != undefined)
	{
		var infowin = new GInfoWindow();
		//window.console.log(snr);
		infowin.set(n2, "<div style='width:20px;height:20px;'>"+snr+"</div>");
		//infowin.showWindow();
		infowin.setOpacity(0.5);
		mapObj.addOverlay(infowin);

		infowin.showWindow();

		GEvent.addListener(pt, "mouseover", function d(){showList2(snr);});
	}
	else
	{
		var iconUrl = "http://static.naver.com/maps/ico_spot"+i+".gif";
		var marker = new NMark(n1, new NIcon(iconUrl, size, offset));
		mapObj.addOverlay(marker);
		GEvent.addListener(marker, "click", function d(){showList(snr);});
	}

	*/

	return;
}
function showList2(list)
{
	document.getElementById("infoWin2").innerHTML = list;
}
function showList(list)
{
	document.getElementById("infoWin").innerHTML = list;
}
function hideList()
{
	//document.getElementById("infoWin").style.visibility = "hidden";
	document.getElementById("infoWin").innerHTML = "";
}

function getAPRawData(bssid)
{
	var xmlhttp = GetXmlHttpObject();
	//xmlhttp.setType(0);
	var url = "getAPRawData.php?bssid="+bssid;
	xmlhttp.open('GET', url, true);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
			showAPRawData(xmlhttp.responseText);
	}
	xmlhttp.send(null);
}

function showAPRawData(res)
{
	//window.console.log(str);
	//window.console.log("showAPRawData");
	eval("var s = " + res +";");

	//window.console.log("showAPRawData");
	//eval(str);
	document.getElementById('totalNum').innerHTML = "총 AP : "+s.totalNum + "개";
	//mapObj.clearOverlays();
	clearMarkers();

	//boundary를 구하기 위해
	//do not get bounds. this function returns bigger bound than that of the current viewport
	//var bounds = mapObj.getBounds();
	var bounds = new google.maps.LatLngBounds();

	for(var i in s.Points)
	{
		var node = s.Points[i];
		var p = new google.maps.LatLng(node.latitude, node.longitude);
		bounds.extend(p);
		/*
		var str = "";
		for(var key in node)
		{
			if(node[key] != "")
				str += key + ":" + node[key] + "<BR>";
		}
		*/

		var str = "snr:"+node.snr + "<BR>signal:"+node.signal+"<BR>detect:"+node.detectTime;
		str += "<BR>submitID:"+node.submitId+"<BR>velocity:"+node.velocity+"<BR>hdop:"+node.hdop;
		//window.console.log(str);

		addmarker(node.latitude, node.longitude, 0, str, 1);
	}
	//var b = line.getBound();
	//mapObj.setBound(b[0], b[1], b[2], b[3]);

	//mapObj.setCenter(bounds.getCenter(),mapObj.getBoundsZoomLevel(bounds));
	mapObj.fitBounds(bounds);
	var z = mapObj.getZoom();
	//currently, google map does not support the zoom more than 18
	if(z > 18)
		mapObj.setZoom(18);
	//window.console.log(z);
	//window.console.log(bounds);


	//do not execue getAPPos() function one time
	donotChangeMap = 1;

	document.getElementById('waiting').style.visibility = "hidden";

}

function showAPPoints(res)
{
	//window.console.log("showAPPoints()");
	eval("var s = " + res +";");
	document.getElementById('totalNum').innerHTML = "총 AP : "+s.totalNum + "개";
	//MapPanes.overlayLayer = null;
	//mapObj.clearOverlays();
	clearMarkers();
	for(var i in s.Points)
	{
		var node = s.Points[i];
		//window.console.log(i);
		addmarker(node.lat, node.lng, node.no, node.lists);
	}
	document.getElementById('waiting').style.visibility = "hidden";
}
//ruler 관련 코드
var rulerStatus = 0;
//최소 AP 개수
var minAPNum = 1;

var pt1, pt2;
function changeMinAPNum()
{
	var obj = document.getElementById('minAPNum');
	minAPNum = obj.value;

	getAPPoints();
}
function rulerCheck(p)
//function rulerCheck(overlay, latlng)
{
	/*
	var iconURL = "img/point_blue.png";
	var size = new NSize(7, 8);
	
	if(rulerStatus == 1)
	{
		var marker = new NMark(p, new NIcon(iconURL, size)); 
		mapObj.addOverlay(marker);
		pt1 = p;
		rulerStatus++;
	}
	else if(rulerStatus == 2)
	{
		var marker = new NMark(p, new NIcon(iconURL, size)); 
		mapObj.addOverlay(marker);
		pt2 = p;
		rulerStatus = 1;

		//polyline
		var line = new NPolyline();
		line.addPoints(pt1, pt2);
		line.setColor('#0000FF');
		mapObj.addOverlay(line);

		//거리측정
		var dis = pt1.distanceFrom(pt2);

		var infowin = new NInfoWindow();
		infowin.set(p, '<div class=distance>'+dis+' m</div>');
		infowin.setOpacity(1);
		mapObj.addOverlay(infowin);
		infowin.showWindow();

		//window.console.log(dis);
		//document.getElementById('logTime').innerHTML += "<br>\nDistance : "+dis+" m";

	}
	*/
}
function changeRulerState()
{
	/*
	if(rulerStatus == 0)
	{
		document.getElementById('rulerButton').innerHTML = "Ruler on";
		rulerStatus = 1;
	}
	else
	{
		document.getElementById('rulerButton').innerHTML = "Ruler off";
		rulerStatus = 0;
	}
	*/
}
//ruler 관련 코드 끝

//debug variable
//var ggg = 0;
function getAPPoints()
{
	//window.console.log("getAPPoints " + ggg++);
	
	if(donotChangeMap > 0)
	{
		donotChangeMap--;
		return;
	}


	var b = mapObj.getBounds();
	if(b == null)
	{
		window.console.log("bounds null");
		return;
	}
	//ruler가 동작 중일 때는 동작 안함
	if(rulerStatus != 0)
		return;
	//var lt = mapObj.fromTM128ToLatLng(new NTM128(b[0], b[1]));
	//var rb = mapObj.fromTM128ToLatLng(new NTM128(b[2], b[3]));
	var lt = b.getSouthWest();
	var rb = b.getNorthEast();
	var obj = document.getElementById('waiting');
	obj.style.visibility = "visible";
	var xmlhttp = GetXmlHttpObject();
	if(xmlhttp == null) 
		window.console.log("xml null");
	var url = "getAPs.php?b1="+rb.lat()+"&b2="+lt.lng()+"&logSelect="+logSelect;
	url = url + "&b3="+lt.lat() +"&b4="+rb.lng();
	url = url + "&sourceNum="+minAPNum;
	//window.console.log(url);
	xmlhttp.open('GET', url, true);
	xmlhttp.onreadystatechange = function()
	{
		if(xmlhttp.readyState == 4)
		//window.console.log(xmlhttp.responseText);
		showAPPoints(xmlhttp.responseText);
	}
	xmlhttp.send(null);
}

var logSelect = 1;
function loadLog()
{
	var obj = document.getElementById('log');
	logSelect = obj.value;
	getAPPoints();
}


</script>
</head>
<body onload="initialize()">
  <div id="map_canvas" style="width:100%; height:100%"></div>
<div id="display"></div>
<div id="infoWin"></div>
<div id="infoWin2"></div>
<div id="minAPNumDiv">최소 AP 검출 지역 : 
<div id=waiting><img src=img/wait.gif></div>
<select name=minAPNum id=minAPNum onChange='changeMinAPNum()'>
<?
for($i = 1; $i < 30; $i++)
	echo "<option value=$i>$i 개</option>\n";
?>
</select>
<button id=rulerButton onclick=changeRulerState()>Ruler</button>
<div id=totalNum></div>
</body>
</html>
